let fs = require('fs');
let multer = require('multer');
const db = require('../dao/database')
const nodemailer = require('nodemailer');
let { createRand } = require('../utils/index');
const { email } = require('../dao/email');



const sendEmail = async function (address) {
    let emailCode = createRand(1000, 9999) //验证码为4位随机数
    let emailInfo = {
        title: '邮箱验证码',
        html: `<p>【Liszter邮箱验证码】您的验证码是${emailCode}，在30分钟内有效。如非本人操作请忽略本短信。</p>`
    }
    let emailRes = await email(address, emailInfo)
    // 邮件发送成功保存发送记录到数据库中
    let type = 1
    if (emailRes) {
      RecordEmail(address, emailCode, type)
    }
    return emailRes
}


/**
 * @param email
 * @param code
 * @param type
 * 
*/

const RecordEmail = async function (email, code, type) {
  let createdTime = new Date().getTime()
  let sql = `REPLACE INTO verifycode(email, code, createdTime, type) VALUES('${email}', '${code}', '${createdTime}', '${type}')`
  try {
    let res = await db(sql, [])
    console.log('已存库');
} catch (error) {
    console.log(error);
}

}


// // 邮箱验证码发送接口
// getEmailCode = (req, res) => {
//     let email = req.body.email;
//     console.log(email);
//     // 判断
//     if (sendCodep(email)) {
//         res.send({
//             code: 400,
//             message: '已经发送过了，请稍后再发！'
//         })
//         return
//     }
//     // 调用发送email接口
//     let code = sendEmail(email)


//     console.log(validataPhonecode);
//     // 验证该邮箱是否已经接受过验证码
//     // 报错到发送目录

//     validataPhonecode.push({
//         'email': email,
//         'code': code
//     })

//     console.log(validataPhonecode);
//     // 发送验证码
//     res.send({
//         'code': 200,
//         'message': '验证码已经发送到邮箱！'
//     })
//     console.log(code);
// }

// // 检测是否已经发送过email
// let sendCodep = (email) => {
//     for (let item of validataPhonecode) {
//         if (email == item.email) {
//             return true
//         }
//     }
//     return false
// }


// // 判断发送的email和code 是否一致
// findCodeAndEmail = (email, code) => {

//     console.log(validataPhonecode);
//     for (let item of validataPhonecode) {
//         if (item.email == email && item.code == code) {
//             return 'login'
//         }
//     }
//     return 'error'
// }


const testSend = async function (email) {
  return sendEmail(email)
}

module.exports = {
    sendEmail,
    testSend
}